;
(function (window, angular) {
    'use strict';
    angular.module("Controller.BasicData.CommonQuery", [])
        .controller("CommonQueryCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus) {
            $scope.dataList = [];
            $scope.detailInfo = {
                commonMaintenanceDO: {},
                maintenanceList: [],
                materialList: []
            };
            $scope.activeFlag = [true, false, false, false];
            $scope.markInfo = {
                allCheckedMaterial: false
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMaterielOriginal: false,
                showMaterielDismantling: false
            };
            $scope.newTbConf = {
                fixedWidth: 340,
                scrollWidth: 800,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.flagInfo = {
                type: 0,
                name: '新增'
            };

            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/excipient/exportAllConfig")
            };

            // 切换tab
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                $scope.detailInfo.maintenanceList = [];
                $scope.detailInfo.selectModelName = '';
            };

            // 取消
            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            // 选择零件
            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            // 导入零件
            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/modelMaterial/download",
                    importReqService: "device",
                    importReqUrl: "/modelMaterial/import",
                    importErrorUrl: "",
                    warehouseCode: '',
                    areaCode: ''
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.detailInfo.materialList = [];
                    $scope.detailInfo.materialList = angular.copy(data);
                });
            };

            $scope.search = function () {
                getDataList();
            };

            // 获取保养包列表
            function getDataList () {
                var url = "/commonMaintenance/list";
                var param = {};
                if ($scope.condition.maintenanceName) {
                    param.maintenanceName = $scope.condition.maintenanceName;
                }
                ybHttp.Get('device', url, param).then(function(res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = res.value;
                })
            }

            // 获取机型列表
            function getMaintenanceList (id) {
                var url = '/commonMaintenance/queryModelList';
                ybHttp.Get('device', url, id).then(function(res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.maintenanceList = res.value;
                })
            }

            $scope.selectMaintenance = function () {
                var nameStr = [];
                angular.forEach($scope.detailInfo.maintenanceList, function (item) {
                    if (item.check) nameStr.push(item.modelName);
                });
                $scope.detailInfo.selectModelName = nameStr.join(',');
            };

            // 保存保养包
            $scope.saveData = function () {
                var params = {};
                if ($scope.detailInfo.commonMaintenanceDO.id) {
                    params = getEditSaveParams();
                } else {
                    params = getAddSaveParams();
                }
                var url = '/commonMaintenance/submit';
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    // 保存成功后删除已填的信息 避免下次进入页面再次展示
                    delete $scope.detailInfo.commonMaintenanceDO;
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                })
            };

            // 获取新增时保存调接口时的参数
            function getAddSaveParams () {
                var addModelIdList = [];
                angular.forEach($scope.detailInfo.maintenanceList, function (item) {
                    if (item.check) addModelIdList.push(item.modelId);
                });
                return {
                    addModelIdList: addModelIdList,
                    maintenanceModelIdList: [],
                    maintenanceName: $scope.detailInfo.commonMaintenanceDO.maintenanceName
                };
            }

            // 获取编辑时保存调接口时的参数
            function getEditSaveParams () {
                var addModelIdList = [];                // 添加的机型id 数组
                var maintenanceModelIdList = [];        // 要删除的机型id 数组
                angular.forEach($scope.detailInfo.maintenanceList, function (item) {
                    // 如果机型的状态是选中 并且 没有id 则是新添加的机型
                    if (item.check && !item.id) {
                        addModelIdList.push(item.modelId)
                    }
                    // 如果机型的状态为未选中并且 在原来保养单详情机型列表里 则是要删除的机型
                    if (!item.check && item.id) {
                        maintenanceModelIdList.push(item.id);
                    }
                });
                return {
                    id: $scope.detailInfo.commonMaintenanceDO.id,
                    addModelIdList: addModelIdList,
                    maintenanceModelIdList: maintenanceModelIdList,
                    maintenanceName: $scope.detailInfo.commonMaintenanceDO.maintenanceName
                }
            }

            // 编辑保养包
            $scope.editData = function (id) {
                $scope.flagInfo = {
                    type: 1,
                    name: '编辑'
                };
                var url = '/commonMaintenance/detail';
                ybHttp.Get('device', url, {id: id}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(1);
                    $scope.detailInfo.commonMaintenanceDO = res.value.commonMaintenanceDO;
                    $scope.detailInfo.maintenanceList = res.value.relationVOList;
                    var selectModelName = [];
                    angular.forEach(res.value.relationVOList, function (item) {
                       if (item.check) {
                           selectModelName.push(item.modelName);
                       }
                    });
                    $scope.detailInfo.selectModelName = selectModelName.join(',');
                })
            };

            // 点击新增
            $scope.addData = function () {
                $scope.flagInfo = {
                    type: 0,
                    name: '新增'
                };
                getMaintenanceList();
                $scope.changeTab(1);
            };

            // 删除保养包
            $scope.deleteMaintenance = function (id, index) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var url = '/commonMaintenance/delMaintenance';
                    ybHttp.Post('device', url, [id]).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.dataList.splice(index, 1);
                    })
                })
            };

            // 删除保养包机型关系
            $scope.deleteModel = function (id, index, childIndex) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var url = '/commonMaintenance/delModel';
                    ybHttp.Post('device', url, [id]).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.dataList[index].children.splice(childIndex, 1);
                    })
                })
            };

            // 搜索零件
            $scope.searchMateriel = function () {
                var id =  $scope.detailInfo.modelId;
                $scope.configMaterial(id);
            };

            // 维护零件
            $scope.configMaterial = function (id) {
                var url = '/modelMaterial/associatedMaterialList';
                var params = {
                    filters: {
                        id: id
                    },
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage
                };
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(2);
                    $scope.pageInfo.totalRows = res.value.total;
                    $scope.pageInfo.totalPages = res.value.pages;
                    $scope.detailInfo.materialList = res.value.list;
                    var oldMaterialIds = [];
                    angular.forEach(res.value.list, function (item) {
                        oldMaterialIds.push(item.id);
                    });
                    $scope.detailInfo.oldMaterialIds = oldMaterialIds;
                    $scope.detailInfo.modelId = id;
                })
            };

            // 获取保存机型零件接口的参数
            function getSaveMaterialParams () {
                var params = {};
                var addMaterialsList = [];
                var oldMaterialIds = $scope.detailInfo.oldMaterialIds;
                if (oldMaterialIds && oldMaterialIds.length > 0) {
                    angular.forEach($scope.detailInfo.materialList, function (item) {
                        var index = oldMaterialIds.indexOf(item.id);
                        // 如果有id则是机型已有的零件
                        if (item.id && index >= 0) {
                            oldMaterialIds.splice(index, 1);
                        } else {
                            addMaterialsList.push(item);
                        }
                    });
                    params.delIdList = oldMaterialIds;
                    params.materialsList = addMaterialsList;
                } else {
                    params.materialsList = $scope.detailInfo.materialList
                }
                params.maintenanceModelId = $scope.detailInfo.modelId;
                return params;
            }

            // 保存机型零件
            $scope.saveMaterial = function () {
                var url = '/modelMaterial/submit';
                var params = getSaveMaterialParams();
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(0);
                    ybWidget.ShowToaster('success', '操作成功');
                })
            };

            // 删除零件
            $scope.delMateriel = function (index) {
                $scope.detailInfo.materialList.splice(index, 1);
            };

            // 批量删除零件
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = $scope.detailInfo.materialList.length -1; i >= 0; i--) {
                    if (!!$scope.detailInfo.materialList[i].isChecked) {
                        selectedCount++;
                        $scope.detailInfo.materialList.splice(i, 1);
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                // 全部删除的话 取消全选框选中状态
                if ($scope.detailInfo.materialList.length === 0) {
                    $scope.markInfo.allCheckedMaterial = false;
                }
                EventBus.Publish("setMaterial");
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };

            var btnPermissionCode = {
                commonQueryAdd: window.ActionCode.commonQueryAdd,
                commonQueryEdit: window.ActionCode.commonQueryEdit,
                commonQueryDelete: window.ActionCode.commonQueryDelete,
                commonQueryMaterial: window.ActionCode.commonQueryMaterial
            };

            $scope.btnPermission = {
                commonQueryAdd: true,
                commonQueryEdit: true,
                commonQueryDelete: true,
                commonQueryMaterial: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            (function() {
                getDataList();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);